package com.rest.demo.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @author Administrator
 * @decription
 * @Date 2018-02-09 16:34
 */
public class EpollClient {

    public static void main(String[] args) {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("116.196.84.9",8001));
            ByteBuffer buffer = ByteBuffer.allocate(32);
            ByteBuffer writeBuffer = ByteBuffer.allocate(32);

            ByteBuffer fileBuffer = ByteBuffer.allocate(128);
            FileInputStream inputStream = new FileInputStream(new File("F:\\a.txt"));
            FileChannel fileChannel = inputStream.getChannel();
            int b = -1;
            StringBuffer sb = new StringBuffer();
            while((b = fileChannel.read(fileBuffer)) != -1) {
                fileChannel.read(fileBuffer);
                fileBuffer.flip();
                while(fileBuffer.hasRemaining()) {
                    sb.append(((char) fileBuffer.get()));
                }
                fileBuffer.clear();
            }
            writeBuffer.put(sb.toString().getBytes());
            writeBuffer.flip();
            while(true) {
                writeBuffer.rewind();
                socketChannel.write(writeBuffer);
                buffer.clear();
                socketChannel.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
